#!/bin/bash

# add html index to taisan report

OUTDIR=/home/liubin/share/taisan_report
# MFILE=${1:-/home/liubin/mail/taisan_report/cur/msg.3lrS}
# MFILE=${1:-/home/liubin/mail/taisan_report/cur/msg.BiY}
MFILE=${1:-/home/liubin/mail/inbox/cur/msg.knkN}
LOG_FILE=$OUTDIR/.fmtdone
SUBJECT=
HFILE=
PURE_TEXT=$(tempfile)

INDEX_NAMES=
INDEXS_RAW=

L_LEVEL=0 L_LENGTH=0

function convert_to_html()
{
	local content=$(metamail -w -x $MFILE)
	# echo "$content"
	SUBJECT=$(echo "$content" | sed -n '/^Subject:/{s/^Subject:\s*//;p}')
	HFILE=$(echo "$content" | sed -n '${s/^Wrote file //;p}')
}

function get_index_names()
{
	w3m -T text/html -dump $HFILE > $PURE_TEXT
	# remove 'Please ...' '***_dur ...', just to cover the bad wrote html
	INDEX_NAMES=$(grep '^[[:digit:]]\.[[:digit:]]' $PURE_TEXT | sed -e 's/ [pP]lease .*$//' -e 's/ [a-z]\{3\}_dur is.*$//')
	# echo "$INDEX_NAMES"
}

function echo_blank()
{
	local TAB='&nbsp;&nbsp;&nbsp;&nbsp;'
	for (( i = 0; i < $1; i ++ )) ; do
		echo -n $TAB
	done
}

function add_index()
{
	local mark="$1" mark_r="$2" title="$3"
	local length=${#mark_r}
	local level
	if [ $length -eq $L_LENGTH ] && ! [[ "$mark_r" =~ \.1$ ]] ; then
		level=$L_LEVEL
	else
		level=$(echo -n $mark_r | tr -d [[:digit:]] | wc -m)
		if [[ "$mark_r" =~ \.1$ ]] ; then
			let 'level--'
		fi
		let 'level--'
		[ $level -lt 0 ] && level=0
		if [[ "$mark_r" =~ \.1$ ]] ; then
			L_LEVEL=$((level+1))
		else
			L_LEVEL=$level
		fi
		L_LENGTH=$length
	fi

	if [[ $level -gt 0 ]] ; then
		INDEXS_RAW+="<font size='-$level'>$(echo_blank $level)"
	fi
	INDEXS_RAW+="<a href='#mark_$mark' id='hmark_$mark'>$mark_r ${title}</a><br>"
	if [[ $level -gt 0 ]] ; then
		INDEXS_RAW+="</font>"
	fi
}

function insert_marks()
{
	local sed_str
	while read line ; do
		# echo $line
		local mark_r="${line%% *}"
		local title="${line#* }"
		mark="${mark_r//./_}"
		add_index "$mark" "$mark_r" "$title"
		sed_str+=" -e 's:${line//./\\.}[^<]*:<a href=\"#hmark_$mark\" id=\"mark_$mark\">&</a>:'"
	done < <(echo "$INDEX_NAMES")
	# echo "$INDEXS_RAW"
	# echo "$sed_str"
	eval "sed -i $sed_str $HFILE"

	# insert to head of body
	local tfile=$(tempfile)
	echo "$INDEXS_RAW" > $tfile
	sed -i 's/<\/h1>/\n&\n/' $HFILE
	sed -i "/^<\/h1>$/r $tfile" $HFILE
	rm $tfile
}

function gen_filename()
{
	local title="$1" ext="$2"
	declare -i i=0
	while true; do
		local str="($i)"
		[ $i -eq 0 ] && str=""
		if [ -f "$title${str}.$ext" ] ; then
			i=i+1
		else
			echo "$title${str}.$ext"
			return
		fi
	done
}

function move_clear_file()
{
	# REMOTE_HOST=tracker@localhost:/home/tracker   # test using
	REMOTE_HOST=liubin@192.168.1.246:/home/liubin
	RDIRNAME=taisan_report
	DATE=$(echo "$SUBJECT" | grep -P -o '\d{4}-\d{2}-\d{2}' | head -n 1)
	DATE=${DATE%-*}
	echo $DATE
	TYPE=HE
	[[ "$SUBJECT" =~ ^WASU ]] && TYPE=WASU
	HTYPE=daily
	[[ "$SUBJECT" =~ : ]] && HTYPE=by_hour
	[[ "$SUBJECT" =~ 00:00:00.*00:00:00 ]] && HTYPE=daily
	[[ "$SUBJECT" =~ Hourly ]] && HTYPE=by_hour
	[[ "$SUBJECT" =~ Daily ]] && HTYPE=daily

	local middle=$TYPE/$DATE/$HTYPE
	local subject="${SUBJECT// /_}"
	
	# copy to local dir
	local html=$(gen_filename "$OUTDIR/$middle/$subject" html)
	local text=$(gen_filename "$OUTDIR/$middle/text/$subject" txt)
	echo $html $text
	mkdir -p "$(dirname "$html")" "$(dirname "$text")"
	chmod 0644 $HFILE $PURE_TEXT
	cp $HFILE "$html"
	cp $PURE_TEXT "$text"

	# copy to remote host
	local tdir=$(tempfile)
	rm -f $tdir
	local hs="${html##*/}"
	local ts="${text##*/}"
	html="$tdir/$RDIRNAME/$middle/$hs"
	text="$tdir/$RDIRNAME/$middle/text/$ts"
	echo $html $text
	mkdir -p "$(dirname "$html")" "$(dirname "$text")"
	mv $HFILE "$html"
	mv $PURE_TEXT "$text"
	(
		cd $tdir
		echo scp -r $RDIRNAME $REMOTE_HOST
		scp -r $RDIRNAME $REMOTE_HOST
	)

	# clear
	rm -rf $HFILE $PURE_TEXT $tdir
}

function add_log()
{
	local name=$(basename $MFILE)
	echo ${name%:*} >> $LOG_FILE
}

############ BEGIN ############

convert_to_html
get_index_names
insert_marks
move_clear_file
add_log
